package router

import (
	"apibe/single/src/v1/router/handler"
	"apibe/single/src/v1/service/impl"
	"apibe/single/src/v1/share/crypt"
	"apibe/single/src/v1/share/middler"
	"github.com/gin-gonic/gin"
)

// UserRegister 注册
func UserRegister(c *gin.Context) {
	var u impl.User
	err := c.ShouldBindJSON(&u)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	err = handler.RegisterHandler(&u, c.ClientIP())
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	claims := crypt.CustomClaims{
		Account:  u.Account,
		UserName: u.NickName,
		Ip:       c.ClientIP(),
	}
	token, _ := crypt.NewJWT().CreateToken(claims)
	u.AccessToken = token
	c.Set(middler.RESULT, u)
}

// UserLogin 登录
func UserLogin(c *gin.Context) {
	var in struct {
		Account  string `json:"account"`
		Password string `json:"password"`
	}
	err := c.ShouldBindJSON(&in)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	u, err := handler.LoginHandler(in.Account, in.Password, c.ClientIP())
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	claims := crypt.CustomClaims{
		Account:  u.Account,
		UserName: u.NickName,
		Ip:       c.ClientIP(),
	}
	token, _ := crypt.NewJWT().CreateToken(claims)
	u.AccessToken = token
	c.Set(middler.RESULT, u)
}

// UserUpdate 修改
func UserUpdate(c *gin.Context) {
	var u impl.User
	claims := c.MustGet(middler.CLAIMS).(*crypt.CustomClaims)
	err := c.ShouldBindJSON(&u)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	err = handler.UserUpdateHandler(&u, claims)
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	c.Set(middler.RESULT, u)
}

// UserFindMany 批量查询
func UserFindMany(c *gin.Context) {
	var in struct {
		Filter   map[string]interface{} `json:"filter"`
		Page     int                    `json:"page"`
		PageSize int                    `json:"page_size"`
	}
	err := c.ShouldBindJSON(&in)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	us, total, err := handler.UserFindManyHandler(in.Filter, in.Page, in.PageSize)
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	result := map[string]interface{}{
		"data":  us,
		"total": total,
	}
	c.Set(middler.RESULT, result)
}
